package com.vietnam.power.controller;

import java.util.Iterator;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.vietnam.power.constant.GeneralConstant;
import com.vietnam.power.domain.PatronInfo;
import com.vietnam.power.domain.Product;
import com.vietnam.power.domain.SaleOrder;
import com.vietnam.power.service.AppConfigurationService;
import com.vietnam.power.service.TransactionService;

@Controller
public class CartController {
	private static Logger logger = Logger.getLogger(CartController.class);
	@Autowired
	private MessageSource messageSource;

	@Autowired
	private AppConfigurationService appConfigurationService;
	
	@Autowired
	private TransactionService transactionServicel;

	@RequestMapping(value = { "/addToCart" }, method = RequestMethod.POST)
	public @ResponseBody
	String searchProduct(HttpServletRequest request, HttpServletResponse response, @RequestBody Product currentProduct) {
		logger.debug("product id: " + currentProduct.getId());

		if (request.getSession().getAttribute(GeneralConstant.CART_SESSION) != null) {
			SaleOrder saleOrder = (SaleOrder) request.getSession().getAttribute(GeneralConstant.CART_SESSION);
			Set<Product> products = saleOrder.getProducts();

			Iterator<Product> itr = products.iterator();
			while (itr.hasNext()) {
				Product p = itr.next();
				if (p.getId() == currentProduct.getId()) {
					p.setQuantity(p.getQuantity() + currentProduct.getQuantity());
				}
			}

			if (!products.contains(currentProduct)) {
				products.add(currentProduct);
			}
		} else {
			SaleOrder saleOrder = new SaleOrder();
			saleOrder.addProducts(currentProduct);
			request.getSession().setAttribute(GeneralConstant.CART_SESSION, saleOrder);
		}

		return String.valueOf(((SaleOrder) request.getSession().getAttribute(GeneralConstant.CART_SESSION)).getProducts().size());
	}

	@RequestMapping(value = { "/viewCart" }, method = RequestMethod.GET)
	public ModelAndView viewCart(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView("client/viewCart");
		mav.addObject("pageTitle", messageSource.getMessage("page.header.viewcart", null, LocaleContextHolder.getLocale()));
		return mav;
	}

	@RequestMapping(value = { "/updateCart" }, method = RequestMethod.PUT)
	public @ResponseBody
	String updateCart(HttpServletRequest request, HttpServletResponse response, @RequestBody Product currentProduct) {

		SaleOrder saleOrder = (SaleOrder) request.getSession().getAttribute(GeneralConstant.CART_SESSION);
		Set<Product> products = saleOrder.getProducts();

		Iterator<Product> itr = products.iterator();
		while (itr.hasNext()) {
			Product p = itr.next();
			if (p.getId() == currentProduct.getId()) {
				p.setQuantity(currentProduct.getQuantity());
			}
		}

		return "success";
	}

	@RequestMapping(value = { "/deleteCart" }, method = RequestMethod.DELETE)
	public @ResponseBody
	String deleteCart(HttpServletRequest request, HttpServletResponse response, @RequestBody Product currentProduct) {
		SaleOrder saleOrder = (SaleOrder) request.getSession().getAttribute(GeneralConstant.CART_SESSION);
		Set<Product> products = saleOrder.getProducts();

		Iterator<Product> itr = products.iterator();
		while (itr.hasNext()) {
			Product p = itr.next();
			if (p.getId() == currentProduct.getId()) {
				itr.remove();
			}
		}

		if (products.size() == 0) {
			request.getSession().removeAttribute(GeneralConstant.CART_SESSION);
		}

		return "success";
	}

	@RequestMapping(value = { "/checkOut" }, method = RequestMethod.GET)
	public ModelAndView checkOut(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView("client/checkOut");

		mav.addObject("patronInfo", new PatronInfo());
		mav.addObject("paymentList", appConfigurationService.getPaymentMethod());
		mav.addObject("pageTitle", messageSource.getMessage("page.header.viewcart", null, LocaleContextHolder.getLocale()));
		return mav;
	}

	@RequestMapping(value = { "/confirmOrder" }, method = RequestMethod.POST)
	public ModelAndView confirmOrder(HttpServletRequest request, HttpServletResponse response, @ModelAttribute("patronInfo") PatronInfo patronInfo) {
		ModelAndView mav = new ModelAndView("client/confirmOrder");
		SaleOrder saleOrder = (SaleOrder) request.getSession().getAttribute(GeneralConstant.CART_SESSION);
		saleOrder.setPatronInfo(patronInfo);
		saleOrder.setPaymentMethodName(appConfigurationService.getPaymentMethodById(patronInfo.getPaymentId()).getName());
		transactionServicel.createTransaction(saleOrder);
		
		//remove session
		request.getSession().removeAttribute(GeneralConstant.CART_SESSION);
		
		mav.addObject("saleOrder", saleOrder);
		mav.addObject("pageTitle", messageSource.getMessage("page.header.viewcart", null, LocaleContextHolder.getLocale()));
		return mav;
	}
}
